#pragma once

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

// 函数指针
typedef void(*task_t)();

#define TaskNum 3 // 任务数量

void Print()
{
    std::cout << "task: Print()" << std::endl;
}

void Download()
{
    std::cout << "task: Download()" << std::endl;
}

void Flush()
{
    std::cout << "task: Flush()" << std::endl;
}

task_t tasks[TaskNum]; // 任务列表

// 加载任务
void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 1777); // 随机数种子
    tasks[0] = Print;
    tasks[1] = Download;
    tasks[2] = Flush;
}

// 选择一个任务
int SelectTask()
{
    return rand() % TaskNum;
}

// 执行任务
void ExcuteTask(int num)
{
    if (num < 0 || num > 2)
        return;
    tasks[num]();
}

void work()
{
    while(1)
    {
        int taskcmd = 0;
        // 读取任务码
        int n = read(0, &taskcmd, sizeof(taskcmd));
        if (n == sizeof(int))
        {
            // 读取到一个int的数据，读取成功
            std::cout << "pid is: " << getpid() << ", handler task" << std::endl;
            ExcuteTask(taskcmd);
        }
        else if (n == 0)
        {
            // 读取到文件末尾，写端已经关闭，那么读端也关闭
            std::cout << "sub process: " << getpid() << ", quit" << std::endl;
            break;
        }
    }
}